<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html;charset=UTF-8" %>
<c:if test="${empty sessionScope.user}">
    <c:redirect url="/login"/>
</c:if>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 新闻管理系统</title>
    <link rel="stylesheet" href="<c:url value="/resources/css/admin-style.css"/>">
</head>
<body class="admin-body">
<!-- 侧边栏 -->
<aside class="admin-sidebar">
    <div class="sidebar-header">
        <h2>新闻管理系统</h2>
    </div>
    <nav class="sidebar-nav">
        <a href="<c:url value="/dashboard"/>" class="nav-item">仪表盘</a>
        <a href="<c:url value="/list/news"/>" class="nav-item">新闻管理</a>
        <a href="<c:url value="/list/category"/>" class="nav-item">类型管理</a>
        <c:if test="${sessionScope.role!=3}">
            <a href="<c:url value="/list/user"/>" class="nav-item active">用户管理</a>
        </c:if>
        <a href="<c:url value="/list/comm"/>" class="nav-item">评论管理</a>
        <a href="<c:url value="/logout"/>" class="nav-item logout-item">退出登录</a>
    </nav>
</aside>

<!-- 主内容区 -->
<main class="admin-main">
    <header class="admin-header">
        <h1>用户管理</h1>
        <button id="add-user-btn" class="add-btn" onclick="openUserModal()">+ 添加用户</button>
    </header>

    <!-- 用户表格 -->
    <table class="user-table" id="user-list-table">
        <thead>
        <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>角色</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- JS动态渲染 -->
        <c:forEach items="${userList}" var="user">
            <tr>
                <td>${userList.indexOf(user)+1}</td>
                <td>${user.username}</td>
                <td><c:if test="${user.role==1}">管理员</c:if><c:if test="${user.role==2}">普通用户</c:if><c:if test="${user.role==3}">编辑</c:if></td>
                <td><c:if test="${user.status==1}">正常</c:if><c:if test="${user.status!=1}">禁用</c:if></td>
                <td>${user.create_time}</td>
                <td>
                    <button class="edit-btn" onclick="openUserModal('${user.id}')">修改</button>
                    <button class="delete-btn" onclick="deleteUser('${user.id}')">删除</button>
                    <c:if test="${user.status==1}">
                        <button class="ban-btn" onclick="changeStatus('${user.id}',2)">禁用</button>
                    </c:if>
                    <c:if test="${user.status!=1}">
                        <button class="active-btn" onclick="changeStatus('${user.id}',1)">启用</button>
                    </c:if>
                </td>
            </tr>
        </c:forEach>
        </tbody>
    </table>

    <!-- 添加/编辑用户模态框 -->
    <div id="user-modal" class="modal hidden">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="user-modal-title">添加用户</h3>
                <span id="close-user-modal" class="close-btn" onclick="closeUserModal()">&times;</span>
            </div>
            <div id="user-form">
                <input type="hidden" id="user-id">
                <div class="form-group">
                    <label for="user-username">用户名 <span class="required">*</span></label>
                    <input type="text" id="user-username" required>
                </div>
                <div class="form-group">
                    <label for="user-password">密码 <span class="required">*</span></label>
                    <input type="password" id="user-password" required placeholder="添加时必填，编辑时留空则不修改">
                </div>
                <div class="form-group">
                    <label for="user-role">用户角色 <span class="required">*</span></label>
                    <select id="user-role" required>
                        <option value="1">管理员</option>
                        <option value="2">普通用户</option>
                        <option value="3">编辑</option>
                    </select>
                </div>
                <div class="modal-footer">
                    <button class="save-btn" id="save-btn">保存</button>
                    <button type="button" id="cancel-user-btn" class="cancel-btn" onclick="closeUserModal()">取消
                    </button>
                </div>
            </div>
        </div>
    </div>
</main>
<script src="<c:url value="/resources/js/jquery-3.7.1.min.js"/>"></script>
<c:if test="${sessionScope.role==2 || sessionScope.role==3}">
    <script>
        alert("你没有权限访问该页面");
        history.back();
    </script>
</c:if>
<script>
    function openUserModal(id) {
        if (id != null) {
            $(document).ready(function () {
                $.ajax({
                    url: '/list/edit/user/' + id,
                    type: 'GET',
                    success: function (data) {
                        console.log(data);
                        document.getElementById('user-modal-title').textContent = '编辑用户';
                        document.getElementById('user-id').value = data[0].id;
                        document.getElementById('user-username').value = data[0].username;
                        document.getElementById('user-role').value = data[0].role;
                        // 密码框留空（提示留空不修改）
                        document.getElementById('user-password').required = false;
                        document.getElementById('user-password').placeholder = '留空则不修改密码';
                        document.getElementById('user-modal').classList.remove('hidden');
                    }
                });
            });

            document.getElementById('save-btn').onclick = function () {
                $.ajax({
                    url: '/list/alter/user',
                    type: 'POST',
                    contentType: 'application/json',
                    headers: {
                        'X-Custom-Header': 'value'
                    },
                    data: JSON.stringify({
                        id:id,
                        username: $('#user-username').val(),
                        password: $('#user-password').val(),
                        role: $('#user-role option:checked').val()
                    }),
                    success: function (data) {
                        alert("修改成功！");
                        window.location.reload();
                    },
                    error: function (data) {
                        alert("修改失败！");
                        window.location.reload();
                    }
                });
            }
            return;
        }
        document.getElementById('user-modal').classList.remove('hidden');
        document.getElementById('user-modal-title').textContent = '添加用户';
        // document.getElementById('user-form').reset();
        document.getElementById('user-id').value = '';
        document.getElementById('user-username').required = true;
        document.getElementById('user-password').required = true;
        document.getElementById('user-role').value = 0; // 默认角色

        document.getElementById('save-btn').onclick = function () {
            if (document.getElementById('user-username').value === '' || document.getElementById('user-password').value === '') {
                alert("请填写用户名和密码！");
                return;
            }
            $(document).ready(function () {
                $.ajax({
                    url: '/list/add/user',
                    type: 'POST',
                    data: {
                        username: document.getElementById('user-username').value,
                        password: document.getElementById('user-password').value,
                        role: document.querySelector('#user-role option:checked').value
                    },
                    success: function (data) {
                        alert("添加成功！");
                        window.location.reload();
                    },
                    error: function (data) {
                        alert("添加失败！");
                        window.location.reload();
                    }
                });
            });
        }
    }

    // 关闭用户模态框
    function closeUserModal() {
        document.getElementById('user-modal').classList.add('hidden');
        // 重置密码框占位符
        document.getElementById('user-password').placeholder = '添加时必填，编辑时留空则不修改';
    }

    function changeStatus(id,status){
        $.ajax({
            url: '/list/alter/user',
            type: 'POST',
            contentType: 'application/json',
            headers: {
                'X-Custom-Header': 'value'
            },
            data: JSON.stringify({
                id:id,
                status: status
            }),
            success: function () {
                if(status===1){
                    alert("启用成功！");
                }else {
                    alert("禁用成功！");
                }
                window.location.reload();
            },
            error: function (data) {
                alert("修改失败！");
                // window.location.reload();
            }
        });
    }

    function deleteUser(id){
        if(!confirm("确定删除吗？")){
            return;
        }
        $.ajax({
            url: '/list/del/user/'+id,
            method: 'POST',
            success: function (data) {
                if(data===0){
                    alert("删除失败！请禁用后再删除！");
                    return;
                }
                alert("删除成功！");
                window.location.reload();
            },
            error: function () {
                alert("删除失败！");
                window.location.reload();
            }
        });
    }
</script>
</body>
</html>
                                     